package com.zhongpengcheng.aspect;

import com.zhongpengcheng.blog.util.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 接口访问日志切面，记录WEB接口访问来源、访问目标url、请求方法（GET...）、实际处理请求的方法
 *
 * @author zhongpengcheng
 * @date 2021/08/18 10:59
 **/
@Aspect
@Component
@Slf4j
public class APILogAspect {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void httpPost() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void httpGet() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
    public void httpDelete() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PatchMapping)")
    public void httpPatch() {
    }

    /**
     * 接口前置拦截
     * @param joinPoint 切入点对象
     */
    @Before("httpGet() || httpPost() || httpPatch() || httpDelete()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = Objects.requireNonNull((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        log.info("Source IP={}, URL={}, HTTP Method={}, Class Method={}#{}", getAccessAddress(request),
                request.getRequestURL().toString(), request.getMethod(),
                joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
    }

    private String getAccessAddress(HttpServletRequest request) {
        String nginxRealIP = RequestUtils.getNginxRealIP(request);
        String remoteIP = request.getRemoteAddr();
        return nginxRealIP != null ? nginxRealIP : remoteIP;
    }
}
